const Base = require('./base.js');

const fs = require('fs');
const crypto = require('crypto');
const request = require('request');
const xml2js = require('xml2js');

const TOKEN = "chenyuqingrok";
const APPID = "wx0aa96c4007e10057";
const APPSECRET = "659bff415d4c5e1fcd550606fdad1dec";

/*
let access_data = '';
let access_file = '../config/access-token.json';
if (fs.existsSync(access_file)) {
	access_data = JSON.parse(fs.readFileSync(access_file));
}
*/


// const rawBody = require('raw-body');



module.exports = class extends Base {
  async indexAction() {
    // return this.display();
	
	let me = this;
	
	let echostr = me.ctx.param('echostr');
	// 接入
	if (echostr !== undefined) {
		let signature = me.ctx.param('signature');
		let timestamp = me.ctx.param('timestamp');
		let nonce = me.ctx.param('nonce');
		
		let array = new Array(TOKEN,timestamp,nonce);
		array.sort();
		let str = array.toString().replace(/,/g,"");
		
		let sha1Code = crypto.createHash('sha1');
		var code = sha1Code.update(str,'utf-8').digest("hex");
		
		console.log(code);
		console.log(signature);
		
		if (code == signature) {
			return me.body = echostr;
		}
	} 
	// 已接入的后续操作
	else {
		// 获取 access_token
		//if (access_data == '') {
			/*await request.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+ APPID +'&secret=' + APPSECRET, function(error, response, body){
				console.log(body);
				access_data = body;
				fs.writeFile(access_file, JSON.stringify(body));
				/*await fs.writeFileSync(access_file, JSON.stringify(body), (err) => {
					if (err) throw err;
				});*/
			//});
		//}
		// 执行到这里，已经有了 access_token。
		// 获取微信用户的昵称等微信信息
		
		let inData = '';
		let aaa = '';
		let bbb = null;
		let ccc = '';

		// console.log(me.ctx.request.body);
		console.log(me.ctx.request.body);
		
		let theData = me.ctx.request.body.post.xml
		console.log(theData);

		// rawBody(me.ctx.req)
		//   .then(function (buf) {
		//     res.statusCode = 200
		//     res.end(buf.length + ' bytes submitted')
		//   })
		//   .catch(function (err) {
		//     res.statusCode = 500
		//     res.end(err.message)
		//   });



		return me.body = '<xml>\
			 <ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
			 <FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
			 <CreateTime>1348831860</CreateTime>\
			 <MsgType><![CDATA[text]]></MsgType>\
			 <Content><![CDATA['+ theData.Content +']]></Content>\
			 </xml>';
		
		/*me.ctx.req.on('end', function(data){
			inData += data;
		});
		
		return new Promise((resolve, reject) => {
			this.ctx.req.on('end', function(){
				console.log('------------111-------------');
				console.log(inData);
				console.log('------------444-------------');
			
				xml2js.parseString(inData,  {explicitArray : false}, function(error, json) {
					if (error) return reject(error);
					console.log(json);
					let theData = json.xml;
					console.log(theData.FromUserName);
					resolve('<xml>\
			 <ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
			 <FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
			 <CreateTime>1348831860</CreateTime>\
			 <MsgType><![CDATA[text]]></MsgType>\
			 <Content><![CDATA['+ theData.Content +']]></Content>\
			 </xml>');
				});
			});
		});
		
		
		bbb = await me.ctx.req.on('end', function(){
			console.log('------------111-------------');
			console.log(inData);
			console.log('------------444-------------');
		});
		
		console.log(typeof  bbb);
		
		return me.body = inData;*/
		/*
		console.log('------------11111111111111111-------------');
		console.log(inData);
		// console.log(aaa);
		
		
		return new Promise((resolve, reject) => {
			this.ctx.req.on('end', function(){
				console.log('------------111-------------');
				console.log(inData);
				console.log('------------444-------------');
			
				xml2js.parseString(inData,  {explicitArray : false}, function(error, json) {
					if (error) return reject(error);
					console.log(json);
					let theData = json.xml;
					console.log(theData.FromUserName);
					resolve('<xml>\
			 <ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
			 <FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
			 <CreateTime>1348831860</CreateTime>\
			 <MsgType><![CDATA[text]]></MsgType>\
			 <Content><![CDATA['+ theData.Content +']]></Content>\
			 </xml>');
				});
			});
		}).then(function(data){
			console.log('-------------------');
			console.log(data);
			me.body = data;
		});
		
		bbb = await this.ctx.req.on('end', function(){
			console.log('------------111-------------');
			console.log(inData);
			console.log('------------444-------------');
			
			return new Promise((resolve, reject) => {
				xml2js.parseString(inData,  {explicitArray : false}, function(error, json) {
					if (error) return reject(error);
					console.log(json);
					let theData = json.xml;
					console.log(theData.FromUserName);
					resolve('<xml>\
	 <ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
	 <FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
	 <CreateTime>1348831860</CreateTime>\
	 <MsgType><![CDATA[text]]></MsgType>\
	 <Content><![CDATA['+ theData.Content +']]></Content>\
	 </xml>');
				});
			});
		});
		
		
		
		console.log('------------333-------------');
		console.log(inData);
		console.log('------------bbb-------------');
		console.log(bbb);
		console.log('------------bbb2222-------------');
		
		return me.body = ccc;
		
		
		*/
		
		/*bbb = await this.ctx.req.on('end', function(){
			console.log('------------111-------------');
			console.log(inData);
			console.log('------------444-------------');
			ccc = xml2js.parseString(inData,  {explicitArray : false}, function(err, json) {
				console.log(json);
				let theData = json.xml;
				console.log(theData.FromUserName);
				return me.body = '<xml>\
 <ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
 <FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
 <CreateTime>1348831860</CreateTime>\
 <MsgType><![CDATA[text]]></MsgType>\
 <Content><![CDATA['+ theData.Content +']]></Content>\
 </xml>';
			}); 
		});
		if (inData) {
			console.log('------------'+ (new Date()).toString() +'-------------');
			console.log('------------222-------------');
			console.log(inData);
		}
		console.log('------------333-------------');
		console.log(inData);
		console.log('------------bbb-------------');
		// console.log(bbb);
		console.log('------------bbb2222-------------');
		
		console.log(ccc);
		return me.body = ccc;
		
		console.log('------------'+ (new Date()).toString() +'-------------');
		for(let i = 0; i < 100000000; i++){}
		console.log('------------'+ (new Date()).toString() +'-------------');
		return me.body = 'sssssssssss';
		*/
		/*await xml2js.parseString(inData,  {explicitArray : false}, function(err, json) {
			console.log(json);
			let theData = json.xml;
			console.log(theData.FromUserName);
			return me.body = '<xml>\
<ToUserName><![CDATA['+ theData.FromUserName +']]></ToUserName>\
<FromUserName><![CDATA['+ theData.ToUserName +']]></FromUserName>\
<CreateTime>1348831860</CreateTime>\
<MsgType><![CDATA[text]]></MsgType>\
<Content><![CDATA['+ theData.Content +']]></Content>\
</xml>';
		});*/
		
		// 用户关注
		//let inData = this.post();
		
		// let openid = 
	}
  }
};
